const scripts = require('./scripts/logger');
const configs = require('../../environments/configs');

const logLevels = ['DEBUG', 'INFO', 'WARNING', 'ERROR'];

function use (dbHelper) {
  let level = (configs.env.logLevel || 'DEBUG').toUpperCase();

  return new Logger(dbHelper, level);
}

class Logger {
  constructor(dbHelper, level = 'DEBUG') {
    this.dbHelper = dbHelper;
    this.level = logLevels.indexOf(level);
    this.level = this.level == -1 ? 0 : this.level;
  }

  async _add (message, level = 'DEBUG') {
    let currentLogLevel = logLevels.indexOf(level);

    if (currentLogLevel >= this.level) {
      let detail = typeof message == 'string' ? message : JSON.stringify(message);

      return await this.dbHelper.execute(scripts.addLog, { level, message: detail });
    }
  }

  async debug (message) {
    return await this._add(message, 'DEBUG');
  }

  async info (message) {
    return await this._add(message, 'INFO');
  }

  async error (message) {
    return await this._add(message, 'ERROR');
  }

  async clear () {
    await this.dbHelper.execute(scripts.clear)

    return await this.dbHelper.execute(scripts.resetSequence);
  }

  async search (so) {
    so.pageIndex = so.pageIndex || 1;
    so.pageSize = so.pageSize || 20;

    return await this.dbHelper.queryForList(scripts.datas, so);
  }
}

module.exports = {
  use: use
}